package com.github.binarylei.security.bolt;

import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.IRichBolt;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.io.FileWriter;
import java.util.Map;

/**
 * @author: leigang
 * @version: 2018-04-07
 */
public class WorldWriteBolt implements IRichBolt {

    private static final long serialVersionUID = 1L;
    private OutputCollector collector;

    private FileWriter writer;

    @Override
    public void prepare(Map map, TopologyContext topologyContext, OutputCollector collector) {
        this.collector = collector;
    }

    private boolean flag = true;

    @Override
    public void execute(Tuple tuple) {
        try {
            if (writer == null) {
                this.writer = new FileWriter("d:/test/" + this);
            }

            String word = tuple.getString(0);
            if (flag && word.contains("1")) {
                flag = false;
                throw new RuntimeException("WorldSplitBolt 异常");
            }

            writer.write(word);
            writer.write("\r\n");
            writer.flush();

            collector.emit(tuple, new Values(word));
            collector.ack(tuple);
        } catch (Exception e) {
            e.printStackTrace();
            collector.fail(tuple);
        }
    }

    @Override
    public void cleanup() {

    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("word", "count"));
    }

    @Override
    public Map<String, Object> getComponentConfiguration() {
        return null;
    }
}
